'use client'
import React, {useEffect, useMemo, useState} from "react"
import EmployeePage from "../../../components/dashboardPages/EmployeePage";
import GoodsBrandPage from "../../../components/dashboardPages/GoodsBrandPage";
import GoodsCategoriesPage from "../../../components/dashboardPages/GoodsCategoriesPage";
import MarketOrderDetailPage from "../../../components/dashboardPages/MarketOrderDetailPage";
import MarketOrderPage from "../../../components/dashboardPages/MarketOrderPage";
import MarketPage from "../../../components/dashboardPages/MarketPage";
import RolePage from "../../../components/dashboardPages/RolePage";
import {useNavigate, useLocation} from "react-router-dom";
import {Button, Row, Tabs} from "antd";
import dashboardPageStore from "../../../store/DashboardPageStore";
import {matchPath} from "@nodescript/pathmatcher";
import {DashboardPage} from "../../../components/dashboardPages/DashboardPage";
import {observer} from "mobx-react-lite";
import GoodsPage from "../../../components/dashboardPages/GoodsPage";
import FactoryPage from "../../../components/dashboardPages/FactoryPage";
import GoodsBrandGroupPage from "../../../components/dashboardPages/GoodsBrandGroupPage";
import MarketDeliveryOrderPage from "../../../components/dashboardPages/MarketDeliveryOrderPage";
import MarketDeliveryOrderDetailPage from "../../../components/dashboardPages/MarketDeliveryOrderDetailPage";
import MarketDeliveryOrderCompareWithOriginalOrderPage
    from "../../../components/dashboardPages/MarketDeliveryOrderCompareWithOriginalOrderPage";
import EmployeeOperateRecordPage from "../../../components/dashboardPages/EmployeeOperateRecordPage";
import {ArrowLeftOutlined, ReloadOutlined} from "@ant-design/icons";
import CheckInventoryRecordPage from "../../../components/dashboardPages/CheckInventoryRecordPage";
import DirectSaleClientPage from "../../../components/dashboardPages/DirectSaleClientPage";
import DirectSaleOrderPage from "../../../components/dashboardPages/DirectSaleOrderPage";
import DirectSaleOrderDetailPage from "../../../components/dashboardPages/DirectSaleOrderDetailPage";
import ProcurementSupplierPage from "../../../components/dashboardPages/ProcurementSupplierPage";
import ProcurementPage from "../../../components/dashboardPages/ProcurementPage";
import ProcurementDetailPage from "../../../components/dashboardPages/ProcurementDetailPage";
import ProcurementReceiptPage from "../../../components/dashboardPages/ProcurementReceiptPage";
import ProcurementReceiptDetailPage from "../../../components/dashboardPages/ProcurementReceiptDetailPage";
import GoodsScratchPage from "../../../components/dashboardPages/GoodsScratchPage";
import GoodsScratchDetailPage from "../../../components/dashboardPages/GoodsScratchDetailPage";
import CheckInventoryRecordDetailPage from "../../../components/dashboardPages/CheckInventoryRecordDetailPage";
import MarketCheckInventoryRecordPage from "../../../components/dashboardPages/MarketCheckInventoryRecordPage";
import MarketCheckInventoryRecordDetailPage
    from "../../../components/dashboardPages/MarketCheckInventoryRecordDetailPage";
import MarketDetailPage from "../../../components/dashboardPages/MarketDetailPage";
import GoodsDetailPage from "../../../components/dashboardPages/GoodsDetailPage";
import MarketReturnOrderPage from "../../../components/dashboardPages/MarketReturnOrderPage";
import MarketReturnOrderDetailPage from "../../../components/dashboardPages/MarketReturnOrderDetailPage";
import MarketSaleDocumentPage from "../../../components/dashboardPages/MarketSaleDocumentPage";
import MarketSaleDocumentDetailPage from "../../../components/dashboardPages/MarketSaleDocumentDetailPage";
import MarketMonthSaleDocumentDetailPage
    from "../../../components/dashboardPages/MarketMonthSaleDocumentDetailPage";
import ProcurementSupplierDetailPage from "../../../components/dashboardPages/ProcurementSupplierDetailPage";
import ProcurementReturnPage from "../../../components/dashboardPages/ProcurementReturnPage";
import ProcurementReturnDetailPage from "../../../components/dashboardPages/ProcurementReturnDetailPage";
import ProcurementPaymentRecordPage from "../../../components/dashboardPages/ProcurementPaymentRecordPage";

export interface PageProps {

}

const dashboardPages: DashboardPage<any>[] = [
    EmployeePage,
    GoodsBrandPage,
    GoodsCategoriesPage,
    MarketOrderDetailPage,
    MarketOrderPage,
    MarketPage,
    RolePage,
    GoodsPage,
    FactoryPage,
    GoodsBrandGroupPage,
    MarketDeliveryOrderPage,
    MarketDeliveryOrderDetailPage,
    MarketDeliveryOrderCompareWithOriginalOrderPage,
    EmployeeOperateRecordPage,
    CheckInventoryRecordPage,
    CheckInventoryRecordDetailPage,
    DirectSaleClientPage,
    DirectSaleOrderPage,
    DirectSaleOrderDetailPage,
    ProcurementSupplierPage,
    ProcurementPage,
    ProcurementReturnPage,
    ProcurementDetailPage,
    ProcurementReturnDetailPage,
    ProcurementReceiptPage,
    ProcurementReceiptDetailPage,
    GoodsScratchPage,
    GoodsScratchDetailPage,
    MarketCheckInventoryRecordPage,
    MarketCheckInventoryRecordDetailPage,
    MarketDetailPage,
    GoodsDetailPage,
    MarketReturnOrderPage,
    MarketReturnOrderDetailPage,
    MarketSaleDocumentPage,
    MarketSaleDocumentDetailPage,
    MarketMonthSaleDocumentDetailPage,
    ProcurementSupplierDetailPage,
    ProcurementPaymentRecordPage,
].sort((a, b) => b.path.length - a.path.length)

const DashboardTabsPage: React.FC<PageProps> = (props) => {
    let location = useLocation();
    let path = location.pathname.replace(/^\//, "");
    if (location.search){
        path +=`${location.search}`
    }
    const [prePath, setPrePath] = useState<string>()
    const [selectedTab, setSelectedTab] = useState<string>()
    let navigate = useNavigate();
    const activatedTab = useMemo(() => {
        if (selectedTab) {
            let page = dashboardPageStore.pages.some(value => (value.path === selectedTab));
            if (!page) {
                if (dashboardPageStore.pages.length) {
                    navigate(-1)
                } else {
                    navigate("/", {
                        replace: true
                    })
                }
            }
            return page ? selectedTab : undefined
        } else {
            return undefined
        }
    }, [dashboardPageStore.pages, selectedTab]);
    useEffect(() => {
        if (prePath != path) {
            if (dashboardPageStore.pages.some(page => page.path === path)) {
                setSelectedTab(path)
            } else {
                let matchedPage = findMatchedPage(path);
                if (matchedPage) {
                    setSelectedTab(path)
                    dashboardPageStore.push(path, matchedPage.title)
                } else {
                    console.error(`no matched page for path: ${path}`)
                }
            }
            setPrePath(path)
        }
    }, [path, dashboardPageStore.pages, prePath]);

    function findMatchedPage(path: string) {
        return dashboardPages.find(it => {
            return matchPath(it.path, path);
        })
    }

    const [reloading, setReloading] = useState(false)
    useEffect(() => {
        if (reloading) {
            setTimeout(() => {
                setReloading(false)
            }, 1000)
        }
    }, [reloading]);

    return <>
        <Tabs size={"small"}
              style={{height: "100%"}}
              onChange={key => {
                  navigate("/" + key)
              }}
              renderTabBar={(props, DefaultTabBar) => {
                  return <DefaultTabBar {...props} style={{top: "24px", padding: "0 24px"}}></DefaultTabBar>
              }}
              tabBarExtraContent={{
                  left: <Row>
                      <Button onClick={() => {
                          navigate(-1)
                      }} type={"text"} loading={reloading} icon={<ArrowLeftOutlined/>}/>
                      <Button onClick={() => {
                          setReloading(true)
                          dashboardPageStore.reload(path)
                      }} type={"text"} loading={reloading} icon={<ReloadOutlined/>}/></Row>
              }}
              type={"editable-card"}
              activeKey={activatedTab}
              hideAdd
              onEdit={(e, action) => {
                  if (action === "remove") {
                      dashboardPageStore.remove(e as string)
                  }
              }}
              items={dashboardPageStore.pages.map(it => {
                  let matchedPage = findMatchedPage(it.path)!!;
                  let strings = it.path.split("?");
                  let queryString = strings[1];

                  const query = {};
                  if (queryString){
                      new URLSearchParams(queryString).forEach((value, name) => {
                          query[name] = value
                      })
                  }
                  let params = {
                      ...matchPath(matchedPage.path, strings[0]),
                      ...query,
                  };
                  return ({
                      key: it.path,
                      label: it.title,
                      children: <div key={it.key}
                                     style={{
                                         overflowX: "hidden",
                                         overflowY: "auto",
                                         height: "100%",
                                         padding: 24
                                     }}>{React.createElement(matchedPage, params)}</div>
                  });
              })}/>
    </>
}

export default observer(DashboardTabsPage)
